<?php
namespace app\admin\controller;
use app\common\library\CategoryType;
use app\common\model\Category as CategoryModel;
use think\Db;
use util\Tree;

class Category extends Backend
{
    /**
     * 数据列表页
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/22 22:55
     * Note:
     */
    public function index()
    {
        if($this->request->isAjax()){
            list($where, $sort, $order, $page, $offset, $limit) = $this->buildSearchParams($this->searchFields);
            $rows = Db::name('category')->where($where)->order(['sort'=>'asc', 'id' => 'asc'])->select();
            $rows = $rows ? Tree::dataToList($rows) : [];
            $data = [
                'total' => count($rows),
                'rows' => $rows,
            ];
            return json($data);
        }

        $type = $this->request->param('type/s','');
        $types = CategoryType::getAllType();
        if(empty($type) && !empty($types[0]['key'])) {
            $type = $types[0]['key'];
        }
        $this->assign('types', $types);
        $this->assign('ctype', $type);
        return $this->fetch();
    }

    /**
     * 新增
     * @return mixed
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/22 22:55
     * Note:
     */
    public function add()
    {
        if($this->request->isGet()){
            $type = $this->request->param('type/s','');
            if(empty($type)) {
                $this->error('类型有误');
            }

            $categorys = CategoryModel::getAllCategoryByType($type);

            $this->assign('categorys',Tree::dataToList($categorys));
            $this->assign('ctype', $type);
            $this->assign('max_depth', CategoryType::getTypeMaxDepth($type));
        }
        return parent::add();
    }


    /**
     * 修改
     * @return mixed
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/22 22:55
     * Note:
     */
    public function edit()
    {
        if($this->request->isGet()){
            $id = $this->request->param('id/d',0);
            if(empty($id)) {
                $this->error('参数有误');
            }
            $type = CategoryModel::getTypeById($id);
            $categorys = CategoryModel::getAllCategoryByType($type);
            $this->assign('max_depth', CategoryType::getTypeMaxDepth($type));
            $this->assign('categorys',Tree::dataToList($categorys));
        }
        return parent::edit();
    }

}